package org.example.rtc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.example.rtc.model.entity.SpeMsg;
import org.example.rtc.model.entity.dto.R;
import org.example.rtc.service.SpeMsgService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/msg")
@RequiredArgsConstructor
public class MsgApi {

    private final SpeMsgService speMsgService;
    private final SimpMessagingTemplate messagingTemplate;

    @PostMapping("/addMsg")
    public void addMsg(@RequestBody List<SpeMsg> speMsg) {
        speMsgService.saveBatch(speMsg);
        for (SpeMsg msg : speMsg) {
            messagingTemplate.convertAndSend("/topic/" + msg.getSpecialistIdTo(), msg.getApplyMsg());
        }
    }

    @PostMapping("/updateMsg")
    public void updateMsg(@RequestBody SpeMsg speMsg) {
        speMsgService.updateById(speMsg);
    }

    @GetMapping("getSendMsg/{id}")
    public R<List<SpeMsg>> getSendMsg(@PathVariable Long id) {
        List<SpeMsg> list = speMsgService.list(
                new LambdaQueryWrapper<SpeMsg>()
                        .eq(SpeMsg::getSpecialistIdFrom, id)
        );
        return R.success(list);
    }

    @GetMapping("getReceive/{id}")
    public R<List<SpeMsg>> getReceive(@PathVariable Long id) {
        List<SpeMsg> list = speMsgService.list(
                new LambdaQueryWrapper<SpeMsg>()
                        .eq(SpeMsg::getSpecialistIdTo, id)
        );
        return R.success(list);
    }

    @GetMapping("getPatDiagnosis/{id}")
    public R<List<SpeMsg>> getPatDiagnosis(@PathVariable Long id) {
        List<SpeMsg> list = speMsgService.list(
                new LambdaQueryWrapper<SpeMsg>()
                        .eq(SpeMsg::getPatId, id)
        );
        return R.success(list);
    }

    @MessageMapping("/sendMessage")
    @SendTo("/topic/messages")
    public String sendMessage(String message) {
        // 处理接收到的消息，并将其发送到/topic/messages
        return message;
    }

    @GetMapping("/sendMsg")
    public void sendMsg(@RequestParam String msg) {
        System.out.println(msg);
        messagingTemplate.convertAndSend("/topic/messages", "Server: " + msg);
    }

}
